/*
Copyright 2010-2011 CumulusCloud
http://cumuluscloud.cc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cumulusCloud.knowledge;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cumulusCloud.common.ManageSession;
import cumulusCloud.common.objects.CloudUser;

public class ServletFilterAdministratorKnow implements javax.servlet.Filter {
	private Logger logger = java.util.logging.Logger.getLogger(ServletFilterAdministratorKnow.class.getName());

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;

		String userToken = ManageSession.getCurrentUserToken(httpServletRequest);
		
		logger.log(Level.INFO, "cloudusertoken: {0}", userToken);
		if (userToken != null) {
			CloudUser cu = ManageSession.getSessionUser(userToken);
			if (cu != null) {
				if (!cu.isAdmin) {
					logger.log(Level.INFO, "user {0} is not an admin", cu.name);
					redirectNotAdmin(httpServletRequest, httpServletResponse);
					return;
				}
			}
		}
		
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {		
	}
	
	private void redirectNotAdmin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter pw = new PrintWriter(response.getOutputStream());
		pw.println("<html><head><title>ccSDK - Not admin</title></head><body>");
		pw.println("<p>You are not an admin</p>");
		pw.println("</body></html>");
		pw.close();
	}
}
